package com.dlwx.parttimetalent.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dlwx.parttimetalent.AlPay.AliPayUtiles;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.bean.AliPayResBean;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.WXPAtResultBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.DialogPayInter;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.ScreenUtils;
import com.dlwx.parttimetalent.utils.SizeUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.views.PayTypeDialog;
import com.dlwx.parttimetalent.wechatpay.WeChatPayUtiles;
import com.dlwx.parttimetalent.wechatpay.wxapi.WXPayResultListener;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RewardActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.flowlayout_money)
    TagFlowLayout flowlayoutMoney;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private int itemWidth;
    private String orderId;
    private String price;
    private String cusPrice;
    private String totalPrice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reward);
        ButterKnife.bind(this);
        int width= ScreenUtils.getScreenWidth();
        itemWidth=(int) (width - SizeUtils.dp2px(40f)) / 4;;
        initView();
    }

    private void initView() {
        orderId=getIntent().getStringExtra("id");
        tvMiddleTitle.setText("打赏");
        tvMiddleTitle.setVisibility(View.VISIBLE);
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        final ArrayList<String> mDatas = new ArrayList<>();;
            mDatas.add("10元");
            mDatas.add("20元");
            mDatas.add("50元");
            mDatas.add("100元");

        flowlayoutMoney.setMaxSelectCount(1);
        final TagAdapter<String> tagAdapter1=new TagAdapter<String>(mDatas) {
            @Override
            public View getView(FlowLayout parent, int position, String price) {
                TextView textView = (TextView) LayoutInflater.from(RewardActivity.this)
                        .inflate(R.layout.tv_label_red_select, flowlayoutMoney, false);
                textView.setText(price);
                textView.getLayoutParams().width = itemWidth;
                return textView;
            }
        };

        flowlayoutMoney.setAdapter(tagAdapter1);
        flowlayoutMoney.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                if(selectPosSet.isEmpty()){
                    price="";
                }else{
                    etMoney.setText("");
                    for(Integer pos:selectPosSet){
                        price=mDatas.get(pos);
                    }
                }
                if(!TextUtils.isEmpty(price)){
                    totalPrice=price.substring(0,price.length()-1);
                }
            }
        });
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
               String str= s.toString();
               if(TextUtils.isEmpty(str)){
                   cusPrice="";
               }else{
                   cusPrice=str;
                   tagAdapter1.notifyDataChanged();
               }
               totalPrice=cusPrice;
            }
        });
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.tv_confirm:

                confirm();
                break;
        }
    }

    private void confirm() {
        if(TextUtils.isEmpty(totalPrice)){
            ToastUtils.toastForShort(this,"请先选择或者自定义打赏金额");
            return;
        }
        PayTypeDialog dialog = new PayTypeDialog(this, new DialogPayInter() {
            @Override
            public void payType(int  payType) {
                aliPay(payType);
//                switch (payType){
//                    case 1:
//                        aliPay(1);
//                        break;
//                    case 2:
//                        break;
//                    case 3:
//                        PayPswDialog dialog=new PayPswDialog(RewardActivity.this, new DialogFilerInter() {
//                            @Override
//                            public void callBack(String datas, String labeid, String sex, String minage, String maxage, String distance) {
//                                yuePay(3,datas);
//                            }
//                        });
//                        dialog.show();
//
//                        break;
//                }
            }
        });
        dialog.show();

    }

    private void aliPay(final int payType) {
        OkgoUtil.post(Http.OrderReward,RewardActivity.this)
                .params("rewardprice",totalPrice)
                .params("orderid",orderId)
                .params("paytype",payType)
                .params("paypwd","")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        AliPayResBean parentBean= DealResult.getInstance().dealDatas(RewardActivity.this,response,new TypeToken<AliPayResBean>() {}.getType());
//                        if(parentBean==null){return;}
//                        int code=parentBean.getCode();
//                        if(code== Constant.SUCESS){
//                            AliPayUtiles utiles=new AliPayUtiles(RewardActivity.this,parentBean.getBody());
//                            utiles.setOnResultListener(new AliPayUtiles.PayResultOnListener() {
//                                @Override
//                                public void getResult(Boolean result) {
//                                    if(true){
//                                        RewardActivity.this.finish();
//                                    }
//                                }
//                            });
//                            utiles.startPay();
//                        }else{
//                            ToastUtils.toastForShort(RewardActivity.this,parentBean.getResult());
//                        }
                        switch (payType){
                            case 1:
                                AliPayResBean parentBean = DealResult.getInstance().dealDatas(RewardActivity.this
                                        , response, new TypeToken<AliPayResBean>() {
                                        }.getType());
                                if (parentBean == null) {
                                    return;
                                }
                                if(parentBean.getCode()==Constant.SUCESS){
                                    AliPayUtiles utiles = new AliPayUtiles(RewardActivity.this, parentBean.getBody());
                                    utiles.setOnResultListener(new AliPayUtiles.PayResultOnListener() {
                                        @Override
                                        public void getResult(Boolean result) {
                                            if (result) {
                                                Intent i=new Intent(RewardActivity.this, MainActivity.class);
                                                i.putExtra("type",1);
                                                startActivity(i);
                                                ToastUtils.toastForShort(RewardActivity.this,"打赏成功");
                                            }
                                        }
                                    });
                                    utiles.startPay();
                                }
                                ToastUtils.toastForShort(RewardActivity.this, parentBean.getResult());
                                break;
                            case 2:
                                WXPAtResultBean wxParentBean = DealResult.getInstance().dealDatas(RewardActivity.this
                                        , response, new TypeToken<WXPAtResultBean>() {
                                        }.getType());
                                if (wxParentBean == null) {
                                    return;
                                }
                                if(wxParentBean.getCode()==Constant.SUCESS) {
                                    WeChatPayUtiles weChatPayUtiles = new WeChatPayUtiles(RewardActivity.this);
                                    weChatPayUtiles.WXPay(wxParentBean.getBody());
                                    weChatPayUtiles.setResult(new WXPayResultListener() {
                                        @Override
                                        public void setResult(boolean result) {
//                                            ToastUtils.toastForShort(RewardActivity.this,"打赏成功");
                                        }
                                    });
                                }
//                                ToastUtils.toastForShort(RewardActivity.this, wxParentBean.getResult());
                                break;
                        }

                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(RewardActivity.this,getString(R.string.bad_net));
                    }
                });
    }
    private void yuePay(int payType,String psw) {
        OkgoUtil.post(Http.OrderReward,RewardActivity.this)
                .params("rewardprice",totalPrice)
                .params("orderid",orderId)
                .params("paytype",payType)
                .params("paypwd",psw)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        BaseBean parentBean= DealResult.getInstance().dealDatas(RewardActivity.this,response,new TypeToken<BaseBean>() {}.getType());
                        if(parentBean==null){return;}
                        int code=parentBean.getCode();
                        if(code== Constant.SUCESS){

                        }else{
                            ToastUtils.toastForShort(RewardActivity.this,parentBean.getResult());
                        }

                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(RewardActivity.this,getString(R.string.bad_net));
                    }
                });
    }
}
